'use client'
import React, { useRef, useState, useMemo } from 'react'
import { HTMLAttributes } from 'react'
import { uploadService, type UploadResponse } from '@/services'
import { toast } from '@/hooks/use-toast'
import { cn } from '@/lib/utils'

interface TriggerProps {
  url: string
  fileInfo: null | File
  isLoading: boolean
  clearInfo: () => void
}
interface FileUploadClientProps extends HTMLAttributes<HTMLDivElement> {
  // 触发器
  trigger?: (options: TriggerProps) => React.ReactNode
  className?: string
  useLoading?: boolean
  onUpload?: (fileUrl: string, file?: File) => void
  onLoading?: (isLoading: boolean) => void
  accept: string // 文件类型, 如'image/*', 'audio/*', 'video/*'
  maxSize: number
  // 按需执行上传
  onExecUpload?: (upload: () => Promise<UploadResponse | null>) => void
}

const FileUploadButton: React.FC<FileUploadClientProps> = ({
  trigger,
  className,
  onUpload,
  onLoading,
  onExecUpload,
  accept,
  maxSize,
  useLoading = false,
  ...otherProps
}) => {
  const [isLoading, setIsLoading] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [uploadUrl, setUploadUrl] = useState<string>('')
  const [currentFile, setCurrentFile] = useState<null | File>(null)
  const handleClick = () => {
    fileInputRef.current?.click()
  }
  const maxSizeMb = useMemo(() => maxSize / 1024 / 1024, [maxSize])
  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file && file.size <= maxSize) {
      setCurrentFile(file)
      if (onExecUpload) {
        onExecUpload(async () => {
          let result = null
          if (onLoading) {
            onLoading(true)
          }
          setIsLoading(true)
          try {
            result = await uploadService.uploadFile(file, (progress) => {
              console.log(`上传进度: ${progress}%`)
            })
            console.log('上传成功:', result, '\n', result.url)
            setUploadUrl(result.url)
          } catch (error) {
            console.error(error)
          } finally {
            setIsLoading(false)
            if (onLoading) {
              onLoading(false)
            }
          }
          event.target.value = ''
          return result
        })
        return
      }
      if (onLoading) {
        onLoading(true)
      }
      setIsLoading(true)
      let fileUrl = ''
      try {
        const result = await uploadService.uploadFile(file, (progress) => {
          console.log(`上传进度: ${progress}%`)
        })
        console.log('上传成功:', result, '\n', result.url)
        fileUrl = result.url
        if (onUpload) {
          onUpload(fileUrl, file)
        }
        setUploadUrl(fileUrl)
      } catch (error) {
        console.error(error)
      } finally {
        setIsLoading(false)
        if (onLoading) {
          onLoading(false)
        }
      }
    } else {
      toast({
        variant: 'destructive',
        description: `上传的文件超过了最大限制（${maxSizeMb}MB）`,
        duration: 3000,
      })
    }
    event.target.value = ''
  }

  const triggerInfo: TriggerProps = useMemo(() => {
    return {
      url: uploadUrl,
      fileInfo: currentFile,
      isLoading,
      clearInfo: () => {
        setUploadUrl('')
        setCurrentFile(null)
      },
    }
  }, [uploadUrl, currentFile, isLoading])

  return (
    <div className={cn(className, 'relative')} onClick={handleClick} {...otherProps}>
      {trigger ? trigger(triggerInfo) : null}
      {otherProps.children}
      {useLoading && isLoading && (
        <div className="absolute inset-0 bg-black/30 z-10 flex justify-center items-center">
          正在获取~
        </div>
      )}
      <input
        type="file"
        accept={accept}
        onChange={handleFileChange}
        ref={fileInputRef}
        className="hidden"
      />
    </div>
  )
}

export default FileUploadButton
